//
// Created by Felix on 24-4-29.
//

#include "LocalizationService.hpp"

LocalizationService::LocalizationService() {
    const std::string filenameZh = "resources/locales/zh.json";
    {
        std::ifstream file(filenameZh);
        if (file) {
            file >> langDataZh;
        } else {
            std::cerr << "Failed to open language file: " << filenameZh << std::endl;
        }
    }

    const std::string filenameEn = "resources/locales/en.json";
    {
        std::ifstream file(filenameEn);
        if (file) {
            file >> langDataEn;
        } else {
            std::cerr << "Failed to open language file: " << filenameEn << std::endl;
        }
    }
}

std::string LocalizationService::getText(
        const std::string &key, const std::string &language
) {
    nlohmann::json::iterator it;
    if (language == "zh") {
        it = langDataZh.find(key);
        if (it != langDataZh.end()) {
            return it->get<std::string>();
        }
    }
    if (language == "en") {
        it = langDataEn.find(key);
        if (it != langDataEn.end()) {
            return it->get<std::string>();
        }
    }
    return key;
}

std::string LocalizationService::getHttpMessage(
        const std::string &key, const std::string &language
) {
    std::string prefix = "zh";
    if (language.substr(0, prefix.size()) == prefix) {
        return getText(key, "zh");
    }
    prefix = "en";
    if (language.substr(0, prefix.size()) == prefix) {
        return getText(key, "en");
    }
    return getText(key);
}
